﻿using ebMS3dotnet.Core.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace ebMS3dotnet.Core
{
    public class ebMS3ChannelFactory<TChannel>:ChannelFactory<TChannel>
    {
        private PMode _pMode;
        public ebMS3ChannelFactory(string pMode)
        {
            InitializePModeFromConfiguration(pMode);
            InitializeBaseFromPMode();
        }

        //public ebMS3ChannelFactory(PMode pMode)
        //{
        //    _pMode = pMode;
        //    InitializeBaseFromPMode();
        //}

        private void InitializeBaseFromPMode()
        {
            ebMS3Binding binding =
            new ebMS3Binding(new Uri(_pMode.MEP),
                new Uri(_pMode.MEPBinding),
                _pMode.SOAPVersion);
            EndpointAddress endpointAddress = new EndpointAddress(_pMode.Address);

            InitializeEndpoint(binding, endpointAddress);
        }

        public TChannel CreateUserMessageChannel()
        {
            UserMessageInfo userMessage = InitializeUserMessageFromPMode();
            return this.CreateChannelForUserMessage<TChannel>(userMessage);
        }

        private UserMessageInfo InitializeUserMessageFromPMode()
        {
            ebMS3Context context = new ebMS3Context();
            ebMS3ContextPModeMapper mapper = new ebMS3ContextPModeMapper();

            mapper.PopulateContextFromPModeForUserMessage(context, _pMode);

            return context.UserMessage;
        }

        private void InitializePModeFromConfiguration(string pModeID)
        {            
            PModeCollection pModes = ebMS3ConfigurationSection.GetSection().PModes;
            if (pModes.Count == 0)
                throw new ConfigurationErrorsException("No PModes were present in the configuration file.");


            _pMode = pModes[pModeID];
            if(_pMode == null)
                throw new ConfigurationErrorsException(string.Format("The PMode with id {0} was not found in the configuration file.", pModeID));
        }
    }
}
